package com.assets.Check.newTanWanCheck;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.assets.Back.back;
import com.assets.BaseActivity;
import com.assets.R;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.Receives;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.Returns;
import com.assets.room.entity.Scrap;
import com.assets.room.entity.ScrapScrapdetail;
import com.assets.room.entity.User;
import com.assets.room.entity.Worker;
import com.assets.util.IdWorkerUtil;
import com.assets.util.MyOkHttp;
import com.assets.util.RequestResult;
import com.assets.util.Since_case;
import com.bigkoo.alertview.AlertView;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Response;

public class BaseActivity1 extends AppCompatActivity {
    /***封装toast对象**/
    private static Toast toast;
    /***获取TAG的activity名称**/
    protected final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /**
     * 显示短toast
     *
     * @param msg
     */
    public void showToast(final String msg) {
        runOnUiThread(() -> {
            if (toast != null) {
                toast.cancel();
            }
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            toast.show();
        });
    }

    private AlertView alertView;

    public void showTipDialog(RequestResult<Boolean> result, String msg) {
        this.runOnUiThread(() -> {
            if (this.alertView == null || !this.alertView.isShowing()) {
                this.alertView = new AlertView("提示", msg, "取消", new String[]{"确认"}, (String[]) null, this, AlertView.Style.Alert, (o, position) -> {
                    this.alertView.dismissImmediately();
                    if (position == -1) {
                        result.result(false);
                    }
                    if (position == 0) {
                        result.result(true);
                    }
                });
                this.alertView.setCancelable(false);
                this.alertView.show();
            }
        });
    }

    //加载进度弹窗
    private volatile ProgressDialog progressDialog;

    public void showDialog(String title) {
        runOnUiThread(() -> {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            progressDialog.setTitle(title);
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setCancelable(true);
            progressDialog.show();
        });
    }

    public void canDialog() {
        runOnUiThread(() -> {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.cancel();
                }
            }
        });
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {//2000毫秒
                //大于2000ms则认为是误操作，使用Toast进行提示
         /*       showToast("再按一次返回");*/
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();//上次点击时间
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected interface result {
        void error();
    }

    public void newLoadGet(String url, RequestResult<String> result) {



    }

    public void newPostScrap(String url, Map<String, String> param, RequestResult<String> result, result error) {

        //todo 对应访问网络接口的事情在这里自己做
//        map.put("assetNumbers", numbers.toString());
//        map.put("userId", Since_case.getInstance().getUserId());
//        map.put("operator", Since_case.getInstance().getUserId());
//        map.put("remark", et.getText().toString());
//        map.put("reason", et_reason.getText().toString());
//        map.put("reasons", remarks.toString());
        String assetNumbers = param.get("assetNumbers");
        String assetNumbers1 = param.get("assetNumbers");
        String userId = param.get("userId");
        String remark = param.get("remark");
        String reason = param.get("reason");

        Scrap scrap = new Scrap();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", 0);

        SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");

        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        scrap.setScrapId(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(12)));
        scrap.setUserId(Since_case.getInstance().getUserId());

        assetNumbers1 = assetNumbers1.substring(1, assetNumbers1.length() - 1);
        assetNumbers1 = assetNumbers1.replace(" ", "");
        String[] numbers1 = assetNumbers1.split(",");

//        Worker worker = MyDataBase.init(BaseActivity1.this).workerService().getWorkerById(Since_case.getInstance().getUserId());
        User user = MyDataBase.init(BaseActivity1.this).userDao().getUserById(Since_case.getInstance().getUserId());
        if (user != null) {

                scrap.setDeptId(String.valueOf(user.getDeptId()));



        }
        Asset asset1 = MyDataBase.init(BaseActivity1.this).assetDao().queryAllByIdSao(numbers1[0]);
        if (asset1 != null) {
          /*  Dept deptById = MyDataBase.init(BaseActivity1.this).deptDao().getDeptById(asset1.getDeptId());
            if (deptById != null) {*/
                scrap.setCompany(String.valueOf(asset1.getCompany()));
           /* }*/
        }else {
            scrap.setCompany("暂无所属位置");
        }

        scrap.setStatus("0");//申请中
        scrap.setCreatedate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        scrap.setOperator(Since_case.getInstance().getUserId());
        scrap.setRedate(nowTime);
        scrap.setRemark(remark);
        scrap.setIsFlag("1");

        MyDataBase.init(BaseActivity1.this).scrapService().insert(scrap);

        assetNumbers = assetNumbers.substring(1, assetNumbers.length() - 1);
        assetNumbers = assetNumbers.replace(" ", "");
        String[] numbers = assetNumbers.split(",");

//        reason = reason.substring(1, reason.length() - 1);
//        reason = reason.replace(" ", "");
//        String[] reasonss = reason.split(",");
        for (int i = 0; i < numbers.length; i++) {

            Asset asset = MyDataBase.init(BaseActivity1.this).assetDao().getNumberByIds(numbers[i]);
            if (asset != null) {
                // 添加明细
                ScrapScrapdetail scrapdetailModel = new ScrapScrapdetail();
                scrapdetailModel.setScrapDetailId(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(12)));
                scrapdetailModel.setScrapId(String.valueOf(scrap.getScrapId()));
                scrapdetailModel.setAssetId(String.valueOf(asset.getAssetId()));
                scrapdetailModel.setText(remark);
                //scrapdetailModel.setReason(reasonss[i]);
                scrapdetailModel.setIsaudit("-");
                scrapdetailModel.setIsfinish("-");
                scrapdetailModel.setStatus("1");
                scrapdetailModel.setIsFlag("1");
//                scrapdetailModel.setReason(reasonss[i]);
                scrapdetailModel.setReason("");
                MyDataBase.init(BaseActivity1.this).scrapScrapdetailService().insert(scrapdetailModel);
                asset.setStatus("2");
                asset.setIsFlag("1");
                MyDataBase.init(BaseActivity1.this).assetDao().updateAsset(asset);
                map.put("state", 1);
                map.put("scrapId", scrap.getScrapId());

            }



        }
        result.result(new Gson().toJson(map));
    }

    public void EPCPostNew(String url, Map<String, String> param, RequestResult<String> result, result error) {

        //todo 这个是读取RFID的接口，本地接口
        //        map.put("assetNumber", scanResult);
//        map.put("userId", Since_case.getInstance().getUserId());
        String assetNumber = param.get("rfid");
//        String rfid = request.getParameter("rfid");
        String userId = param.get("userId");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");

        assetNumber = assetNumber.substring(0, 16);

        User byId = MyDataBase.init(BaseActivity1.this).userDao().getUserById(Since_case.getInstance().getUserId());
        Asset asset = new Asset();

        asset = MyDataBase.init(BaseActivity1.this).assetDao().queryAllById(assetNumber);/*assetService.getOne(new QueryWrapper<Asset>().eq("asset_number", assetNumber));*/
//        if ("3".equals(asset.getStatus().toString())) {
//            //已经报废了
//            showToast("资产：" + asset.getAssetName() + "已经报废了");
//            map.put("state", "6");
//            return;
//        }

        if (asset == null) {
            map.put("state", "2");
        } else if (asset.getStatus().equals("2")) {
            // 资产已报废
            map.put("state", "3");
        } else if (asset.getStatus().equals("3")) {
            // 资产已申请报废
            map.put("state", "5");
        }else {
            Dept company = MyDataBase.init(BaseActivity1.this).deptDao().getDeptById(asset.getCompany());/*deptService.getById(asset.getCompany());*/
            if (company != null) {
                asset.setCompany(company.getSimpleName());
            }
            asset.setDivision("");
            asset.setUserDept("");
            Dept useDept = MyDataBase.init(BaseActivity1.this).deptDao().getDeptById(asset.getDeptId());/*deptService.getById(asset.getDeptId());*/
            if (useDept != null) {
                asset.setDeptId(useDept.getSimpleName());
            }else {
                asset.setDeptId("暂无部门");
            }
//            asset.setDeptId("");
            asset.setAdmin("");
            if (asset.getUserId() != null && !asset.getUserId().equals("")) {

                asset.setUserId(Since_case.getInstance().getUserId());

            }else {
                asset.setUserId("暂无使用人");
            }
            asset.setType(MyDataBase.init(BaseActivity1.this).typeDao().getNameById(asset.getType()));
            map.put("asset", asset);
            map.put("state", "1");
        } /*else {
            map.put("state", "6");
        }*/
        Log.d("我要看看这个自仓", "EPCPostNew: " + new Gson().toJson(map));
        result.result(new Gson().toJson(map));


    }

    public void post(String url, Map<String, String> map, RequestResult<String> result, result error) {
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
                error.error();
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                result.result(responseData);
                //setData(queryData);
            }
        });
    }

    public void newPost(String url, Map<String, String> param, RequestResult<String> result, result error) {

        String userId = param.get("userId").toString();
        String place = param.get("place").toString();
        String assetNumbers = param.get("assetNumbers").toString();
//        String receivesId = param.get("receivesId").toString();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", 0);
//        map.put("userId", Since_case.getInstance().getUserId());
//        map.put("place", site_id);
//        map.put("assetNumbers", numbers.toString());


        assetNumbers = assetNumbers.substring(1, assetNumbers.length() - 1);
        assetNumbers = assetNumbers.replace(" ", "");
        String[] numbers = assetNumbers.split(",");
        List<Returns> ReturnsList = new ArrayList<>();
        List<String> receviesId = new ArrayList<>();
        for (String number : numbers) {
            Log.d("循环的number", "number: " + number);
//            MyDataBase.init(BaseActivity1.this).assetDao().updatePlace();
            MyDataBase.init(BaseActivity1.this).receivesDetailDao().updateFlag("1", "1", number);
            String recevies_id = MyDataBase.init(BaseActivity1.this).receivesDetailDao().getIdById(number);
            receviesId.add(recevies_id);


            if (MyDataBase.init(BaseActivity1.this).returnsDao().getAllData(number).size() == 0) {
                MyDataBase.init(BaseActivity1.this).assetDao().updatePlace(place, "1", "4", number);
                Asset asset = MyDataBase.init(BaseActivity1.this).assetDao().queryAllByNumber(number);
                Returns returns = new Returns();
                returns.setAssetNumber(asset.getAssetNumber());
                returns.setUserId(asset.getUserId());
                returns.setDeptId(asset.getDeptId());
                returns.setUseDept(asset.getUserDept());
                returns.setCompany(asset.getCompany());
                returns.setPlace(asset.getPlace());
                returns.setNplace(place);
                returns.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                returns.setRdate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                returns.setStatus("0");
                returns.setIsFlag("1");
                returns.setReceivesId(MyDataBase.init(BaseActivity1.this).receivesDetailDao().getAssetByIds(number));
                returns.setOperator(userId);

//            MyDataBase.init(BaseActivity1.this).receivesDetailDao().getReceivesDetailById()
//            MyDataBase.init(BaseActivity1.this).assetDao().queryAllByIds()
                ReturnsList.add(returns);
            }else {
//                Toast.makeText(this, "当前资产已归还!", Toast.LENGTH_SHORT).show();
                canDialog();
                map.put("state", 2);
                result.result(new Gson().toJson(map));
                return;
            }

        }

        List<String> myData = new ArrayList<>();
        for (String myRecviesId : receviesId) {

            if (!myData.contains(myRecviesId)) {
                myData.add(myRecviesId);
            }

        }



        Log.d("这个是什么,看一下","receviesId: " + myData);
        MyDataBase.init(BaseActivity1.this).returnsDao().insertAllData(ReturnsList);

        for (String myDatum : myData) {

            int num = Integer.parseInt(MyDataBase.init(BaseActivity1.this).receivesReapplyDao().getNum(myDatum));
            int size = MyDataBase.init(BaseActivity1.this).returnsDao().getAllDataByRID(myDatum).size();
            if (num == size) {
//                isreturn
                MyDataBase.init(BaseActivity1.this).receivesDao().updateStatus("1","1",myDatum);
            }


        }
        map.put("state", 1);
//

        String responseData = new Gson().toJson(map);
        result.result(responseData);
//        for (String number : numbers) {
//            Asset asset = assetService.getOne(new QueryWrapper<Asset>().eq("asset_number", number));
//            model.setAssetNumber(number);
//            model.setUserId(asset.getUserId());
//            model.setDeptId(asset.getDeptId());
//            model.setUseDept(asset.getUserDept());
//            model.setCompany(asset.getCompany());
//            model.setPlace(asset.getPlace());
//            model.setNplace(place);
//            model.setDate(new Date());
//            model.setRdate(new Date());
//            model.setStatus("0");
//            model.setOperator(userId);
//        }
//        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
//            @Override
//            public void requestFail() {
//                showToast("连接服务器失败");
//                error.error();
//            }
//
//            @Override
//            public void requestComplete() {
//                canDialog();
//            }
//
//            @Override
//            public void requestSuccess(Response response) throws IOException {
//                String responseData = response.body().string();
//                result.result(responseData);
//                //setData(queryData);
//            }
//        });
    }

    public void post(String url, Map<String, String> map, RequestResult<String> result) {
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                Log.d("蒋剑华的数据", "responseData: " + responseData);
                result.result(responseData);
                //setData(queryData);
            }
        });
    }

    public void newPostScrapScan(String url, Map<String, String> param, RequestResult<String> result) {

//        map.put("assetNumber", scanResult);
//        map.put("userId", Since_case.getInstance().getUserId());
        String assetNumber = param.get("assetNumber");
//        String rfid = request.getParameter("rfid");
        String userId = param.get("userId");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");

        User byId = MyDataBase.init(BaseActivity1.this).userDao().getUserById(Since_case.getInstance().getUserId());
        Asset asset = new Asset();

        asset = MyDataBase.init(BaseActivity1.this).assetDao().queryAllByIdSao(assetNumber);/*assetService.getOne(new QueryWrapper<Asset>().eq("asset_number", assetNumber));*/

        if (asset == null) {
            map.put("state", "2");
        }else if (asset.getStatus().equals("2")) {
            // 资产已报废
            map.put("state", "3");
        }else if (asset.getStatus().equals("3")) {
            // 资产已申请报废
            map.put("state", "5");
        } else/* if (!asset.getStatus().equals("1"))*/ {
//            // 资产非在用
//            map.put("state", "4");
//            //增强查看全部的权限  lcl  2022-5-23
//        }else if(asset.getStatus().equals("4")) {
            Dept company = MyDataBase.init(BaseActivity1.this).deptDao().getDeptById(asset.getCompany());/*deptService.getById(asset.getCompany());*/
            if(company != null) {
                asset.setCompany(company.getSimpleName());
            }
            asset.setDivision("");
            asset.setUserDept("");
            asset.setDeptId("");
            asset.setAdmin("");
            if(asset.getUserId()!=null && !asset.getUserId().equals("")) {

                    asset.setUserId(Since_case.getInstance().getUserId());

            }
            asset.setType(MyDataBase.init(BaseActivity1.this).typeDao().getNameById(asset.getType()));
            map.put("asset", asset);
            map.put("state", "1");
        }/*else {
            map.put("state", "6");*/
//        }
        result.result(new Gson().toJson(map));

    }

    public void newPost(String url, Map<String, String> rfid, RequestResult<String> result) {
        Log.d("这个东西asset", "assetNumber: " + rfid.get("rfid").toString());
        String rfids = rfid.get("rfid").toString();
        Map<String, Object> map = new HashMap<>();
        map.put("state", "0");

        Asset asset = new Asset();
        if (rfids != null && !"".equals(rfids)) {
            asset = MyDataBase.init(BaseActivity1.this).assetDao().queryAllById(rfids);
        }

        Log.d("这个东西asset", "asset: " + new Gson().toJson(asset));

        if (asset == null) {
            //资产不存在
            map.put("state", "2");
        }else if (asset.getStatus().equals("4") || asset.getStatus().equals("13")) {
            // 资产已归还
            map.put("state", "3");
        }else if (asset.getStatus().equals("3") || asset.getStatus().equals("2")) {
            map.put("state", "999");
        } else if (!asset.getStatus().equals("1") && !asset.getStatus().equals("8")) {
            // 资产不能归还
            map.put("state", "4");
        } else {
            //可以归还的那种资产
            Dept dept = MyDataBase.init(BaseActivity1.this).deptDao().getDeptById(asset.getDeptId());
            if (dept != null) {
                asset.setDeptId(dept.getSimpleName());
            }

            Place place = MyDataBase.init(BaseActivity1.this).placeDao().getAllById(asset.getPlace());
            if (place != null) {
                asset.setType(place.getName());
            }
//
//            ReceivesDetail receivesDetail = MyDataBase.init(BaseActivity1.this).receivesDetailDao().getByTowReceivesDetail(asset.getAssetNumber(), "2");
//
////            if(asset.getStatus().equals("1")) {
////
////                if (receivesDetail != null) {
//////                    Receives receives = receivesDetail.getById(receivesDetail.getReceivesId());
////                    if(receives!=null) {
////                        if(!receives.getStatus().equals("5")) {
//                            //还未复审通过
//                            map.put("state", "5");
//
//                            result.result(new Gson().toJson(map));
////                            return map;
////                        }
////                    }
////
////                }
////
////            }
            map.put("asset", asset);
            map.put("date", "");
            map.put("state", "1");
            Log.d("这个是扫到的东西", "newPost: " + map);

//
        }
        map.put("asset", asset);
        map.put("date", "");
        result.result(new Gson().toJson(map));

    }


    public void newPostSao(String url, Map<String, String> rfid, RequestResult<String> result) {
        Log.d("这个东西asset", "assetNumber: " + rfid.get("rfid").toString());
        String rfids = rfid.get("rfid").toString();
        Map<String, Object> map = new HashMap<>();
        map.put("state", "0");

        Asset asset = new Asset();
        if (rfids != null && !"".equals(rfids)) {
            asset = MyDataBase.init(BaseActivity1.this).assetDao().queryAllByIdSao(rfids);
        }

        Log.d("这个东西asset", "asset: " + new Gson().toJson(asset));

        if (asset == null) {
            //资产不存在
            map.put("state", "2");
        }else if (asset.getStatus().equals("4") || asset.getStatus().equals("13")) {
            // 资产已归还
            map.put("state", "3");
        }else if (asset.getStatus().equals("3") || asset.getStatus().equals("2")) {
            map.put("state", "999");
        } else if (!asset.getStatus().equals("1") && !asset.getStatus().equals("8")) {
            // 资产不能归还
            map.put("state", "4");
        } else {
            //可以归还的那种资产
            Dept dept = MyDataBase.init(BaseActivity1.this).deptDao().getDeptById(asset.getDeptId());
            if (dept != null) {
                asset.setDeptId(dept.getSimpleName());
            }

            Place place = MyDataBase.init(BaseActivity1.this).placeDao().getAllById(asset.getPlace());
            if (place != null) {
                asset.setType(place.getName());
            }
//
//            ReceivesDetail receivesDetail = MyDataBase.init(BaseActivity1.this).receivesDetailDao().getByTowReceivesDetail(asset.getAssetNumber(), "2");
//
////            if(asset.getStatus().equals("1")) {
////
////                if (receivesDetail != null) {
//////                    Receives receives = receivesDetail.getById(receivesDetail.getReceivesId());
////                    if(receives!=null) {
////                        if(!receives.getStatus().equals("5")) {
//                            //还未复审通过
//                            map.put("state", "5");
//
//                            result.result(new Gson().toJson(map));
////                            return map;
////                        }
////                    }
////
////                }
////
////            }
            map.put("asset", asset);
            map.put("date", "");
            map.put("state", "1");
            Log.d("这个是扫到的东西", "newPost: " + map);

//
        }
        map.put("asset", asset);
        map.put("date", "");
        result.result(new Gson().toJson(map));

    }




}
